<script setup lang="ts">
    import { reactive, ref, onMounted } from 'vue'//引入vue函数
    import { getCategoryList, delCategory } from '@/api' //商品分类接口
    import type { Category } from '@/model' //导入自定义数据类型
    import CategoryEdit from './components/CategoryEdit.vue' //分类表单
    import { ElMessage, ElMessageBox } from 'element-plus' //导入消息框

    //表格数据对象
    const tableData = ref<Category[]>([])
    //表格原始数据
    const oldData = ref<Category[]>([])

    //是否显示 添加修改分类对话框
    const isShowDialog =  ref(false)

    //添加修改分类对话框的标题
    const dialogTitle = ref("新增分类")

    //当前将要修改的分类
    const category = reactive({
        id:0,
        name:"",
        pid:-1
    })

    //定义表单数据对象
    const searchForm = reactive({
        name:"",
        level:"0"
    });

    //查询所有商品分类
    async function loadCategoryList(){
        const res = await getCategoryList()
        oldData.value = res.data.data
        convertToTree(oldData.value)
    }

    //将数据转换为树状数据
    function convertToTree(data:Category[]){
        //没查到数据
        if(data == undefined){
            return []
        }
        //处理数据
        var newData:Category[] = []
        //获得所有一级分类
        data.forEach((v)=>{
            if(v.pid == 0){
                newData.push(v)
            }
        })
        //获得二级分类
        newData.forEach((v)=>{
            const result = data.filter((item)=>item.pid==v.id)
            v.children = result
            v.hasChild = result && result.length>0?true:false
        })
        //返回结果
        tableData.value = newData
    }

    //搜索
    function searchCategory(){
        if(searchForm.name == "" && searchForm.level == "0"){
            //查询所有分类
            loadCategoryList()
        }
        else{
            //对现有分类进行过滤
            tableData.value = oldData.value.filter((item:Category)=>{
                item.children = []
                if(searchForm.level == "0"){
                    return item.name?.includes(searchForm.name)
                }
                else if(searchForm.level == "1"){
                    return item.name?.includes(searchForm.name) && item.pid==0
                }
                else{
                    return item.name?.includes(searchForm.name) && item.pid!=0
                }
            })
        }
    }

    //重置表单
    function resetForm(){
        searchForm.name = ""
        searchForm.level = "0"
        convertToTree(oldData.value)
    }

    //新增分类
    function addCategory(){
        dialogTitle.value = "新增分类"
        category.id = 0
        category.name = ""
        category.pid = -1
        isShowDialog.value = true
    }

    //修改分类
    function updateCategory(data:Category){
        dialogTitle.value = "修改分类"
        Object.assign(category, data)
        isShowDialog.value = true
    }

    //关闭对话框
    function closeDialog(){
        isShowDialog.value = false
        loadCategoryList()
    }

    //删除分类
    function deleteCategory(data:Category){
        if(data.hasChild){
            ElMessage.warning("该分类下存在二级分类，请先删除二级分类再删除此分类")
        }
        else{
            //确认对话框
            ElMessageBox.confirm("确定要删除此分类吗？", {
                closeOnClickModal: true,
                confirmButtonText: "确定",
                cancelButtonText: "取消",
            }).then(async ()=>{
                const res = await delCategory({id:data.id})
                if(res.data.errno == 0){
                    //重新加载数据
                    loadCategoryList()
                    //重置搜索表单
                    resetForm()
                    //删除成功
                    ElMessage.success(res.data.errmsg)
                }
                else{
                    //删除失败
                    ElMessage.error(res.data.errmsg)
                }
            }).catch(()=>{
                //console.log("点击了取消按扭")
            })
        }
    }

    //组件加载完成
    onMounted(()=>{
        loadCategoryList()
    })
</script>

<template>

    <!--搜索表单-->
    <section class="search">
        <el-form :inline="true">
            <el-form-item label="分类名称">
                <el-input v-model="searchForm.name" style="width:200px;"></el-input>
            </el-form-item>
            <el-form-item label="分类级别">
                <el-select v-model="searchForm.level" style="width:200px;">
                    <el-option label="所有" value="0"></el-option>
                    <el-option label="一级分类" value="1"></el-option>
                    <el-option label="二级分类" value="2"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="searchCategory">搜索</el-button>
                <el-button @click="resetForm">重置</el-button>
            </el-form-item>
        </el-form>
    </section>

    <!--表格显示内容-->
    <section class="category_page">
        <div><el-button type="primary" @click="addCategory">新增分类</el-button></div>
        <div>
            <!--表格-->
            <el-table :data="tableData" row-key="id" style="width:100%" border>
                <!--空数据时显示内容-->
                <template #empty>暂无数据</template>
                <!--表格有数据时的显示内容-->
                <el-table-column prop="name" label="分类名称"></el-table-column>
                <el-table-column label="分类级别">
                    <template #default="scope">
                        {{ scope.row.pid==0?"一级分类":"二级分类" }}
                    </template>
                </el-table-column>
                <el-table-column prop="id" label="分类编号"></el-table-column>
                <el-table-column label="操作" width="200">
                    <template #default="scope">
                        <el-button type="warning" @click="updateCategory(scope.row)">编辑</el-button>
                        <el-button type="danger" @click="deleteCategory(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
    </section>

    <!--新增分类、修改分类，对话框-->
    <el-dialog v-model="isShowDialog" :title="dialogTitle" width="600">
        <CategoryEdit :is-show="isShowDialog" :category="category" @closeDialog="closeDialog"></CategoryEdit>
    </el-dialog>

</template>

<style scoped>
    .category_page, .search{
        background:#FFFFFF;
        border-radius: 5px;
        box-shadow: 0px 0px 5px 5px #E4E7ED;
        margin:20px;
        border:1px solid transparent;
    }
    .search{
        height:50px;
        padding-left:20px;
        display:flex;
        align-items: center;
    }
    .search .el-form-item{
        margin-top:0px;
        margin-bottom:0px;
    }
    .category_page > div{
        margin:20px;
    }
</style>
